<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>树结构</title>
		<link  rel="stylesheet" href="../css/tree.css"/>
	</head>
	<style>
		.tree{
			width: 600px;
			height: 100vh;
			border: 1px solid black;
		}
	</style>
	<body>
		<div class="tree" id="tree">
			<div id="div"></div>
		</div>
		
		<script>
			
			const list=[{'name':'李四','child':[{'name':'王五'},{'name':'张三','child':[{'name':'王五'},{'name':'张三','child':[{'name':'王五'},{'name':'张三'}]}]}]},{'name':'王五','child':[{'name':'王五'},{'name':'张三'}]}]
			let div=document.getElementById('div');
			
			function generateNestedList(data) {
			  let result = '<ul>';
			  data.forEach(item => {
			    result += '<li class="tree-li">';
				result += '<div class="tree-div">';
				if (item.child && item.child.length > 0) {
					result+='	<a class="img-a"></a>';
					result+='	<img class="tree-img expand-img" src="../img/minus.png" />';
				}
				result += '		<input type="checkbox" />'
				result += '		<a>'+item.name+'</a>'
				result += '</div>';
				if (item.child && item.child.length > 0) {
					 result += generateNestedList(item.child);
				}
				
			    result += '</li>';
			  });
			
			  result += '</ul>';
			  return result;
			}
			const nestedList = generateNestedList(list);
			div.innerHTML=nestedList;
			
		
			const listItem = document.querySelectorAll("ul");
			
			listItem.forEach(function(item) {
			  item.addEventListener("click", function(event) {
				event.stopPropagation();
				if(event.target.tagName=='IMG'){
					let node=event.target.parentNode;
					node=node.parentNode;
					expand(node,event.target);
				}
				if(event.target.tagName=='INPUT'){
					console.log(event.target)
				}
			  });
			});
			
			const liItemsDiv = document.querySelectorAll('.tree-div');
			
			// 为每个 <li> 元素添加事件监听器
			liItemsDiv.forEach((div) => {
			  div.addEventListener('click', function(event) {
				// 移除所有的 selected 类名
			    liItemsDiv.forEach((item) => {
			      item.classList.remove('selected');
			    });
				
				div.classList.add('selected');
			  });
			});
			
			
			
			function expand(e,currentNode){
				if(currentNode.classList.contains("no-expand-img")){
					currentNode.classList.remove("no-expand-img");
					currentNode.classList.add("expand-img")
				}else{
					currentNode.classList.remove("expand-img");
					currentNode.classList.add("no-expand-img")
				}
				const childNodes = Array.from(e.childNodes);
				childNodes.forEach(node => {
					if(node.nodeName=='UL'){
						if(node.classList.contains("no-expand")){
							node.classList.remove("no-expand");
							node.classList.add("expand")
						}else{
							node.classList.remove("expand");
							node.classList.add("no-expand")
						}
					}
				}); 
				
			}
			
			
		</script>
	</body>
</html>